package de.mmis.core.infrastructure.gui;

import java.text.DateFormat;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.AbstractListModel;
import javax.swing.SwingUtilities;

import de.mmis.core.base.event.Observable;
import de.mmis.core.base.event.Observer;
import de.mmis.core.base.infrastructure.InfrastructureEvent;

class LogListModel extends AbstractListModel implements
		Observer<InfrastructureEvent> {

	private static final long serialVersionUID = -6565132549191642336L;

	protected int maxSize;
	protected LinkedList<String> data;

	/**
	 * @param maxSize
	 *            maximum number of lines. -1 means no limit
	 */
	public LogListModel(int maxSize) {
		this.maxSize = maxSize;
		data = new LinkedList<String>();
	}

	@Override
	public Object getElementAt(int index) {
		return data.get(index);
	}

	@Override
	public int getSize() {
		return data.size();
	}

	@Override
	public void notify(Observable<? extends InfrastructureEvent> sender,
			final InfrastructureEvent event) {
		// modify the data in the event dispatching thread
		SwingUtilities.invokeLater(new Runnable() {
			@SuppressWarnings("synthetic-access")
			@Override
			public void run() {
				String s = "["
						+ DateFormat.getDateTimeInstance().format(new Date())
						+ "]";
				s += " " + event.toString();
				data.addLast(s);
				if (maxSize >= 0)
					while (data.size() > maxSize)
						data.removeFirst();
				fireContentsChanged(this, 0, data.size());
			}
		});
	}
}
